package com.example.glidewithsvg.svg

import android.util.Log
import com.bumptech.glide.load.Options
import com.bumptech.glide.load.ResourceDecoder
import com.bumptech.glide.load.engine.Resource
import com.bumptech.glide.load.resource.SimpleResource
import com.caverock.androidsvg.SVG
import com.caverock.androidsvg.SVGParseException
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader

/**
 * SVG 解码器
 *
 * 对于路径是 SVG:true:/thumbnailpath/15.svg 的格式进行处理
 * 格式: SVG:[isSelected]:[svgpath]
 */
class SvgDecoder : ResourceDecoder<InputStream, SVG> {

    companion object {
        const val SVG_FORMAT_PREFIX = "SVG"
        const val TAG = "SvgDecoder"
        const val THUMBNAIL_DEFAULT_COLOR = "#FFFFFF7A"
        const val THUMBNAIL_SELECTED_COLOR = "#F9D005"
    }

    override fun handles(source: InputStream, options: Options): Boolean {
        val filePath = getOriginalPath(source)
        return filePath.startsWith(SVG_FORMAT_PREFIX)
    }

    private fun getOriginalPath(source: InputStream): String {
        val reader = BufferedReader(InputStreamReader(source))
        val sb = StringBuilder()
        var line: String?
        try {
            line = reader.readLine()
            while (line != null) {
                sb.append(line)
                line = reader.readLine()
            }
        } catch (e: IOException) {
            Log.e(TAG, "SvgDecoder getOriginalPath", e)
        }
        return sb.toString()
    }

    override fun decode(
        source: InputStream,
        width: Int,
        height: Int,
        options: Options
    ): Resource<SVG>? {
        return try {
            val filePath = getOriginalPath(source)
            val scheme = filePath.split(":")
            val isSelected = scheme[1].toBoolean()
            val svgFilePath = scheme[2]
            var svgContent = loadSVGContent(isSelected, svgFilePath)
            val svg = SVG.getFromString(svgContent)
            SimpleResource(svg)
        } catch (ex: SVGParseException) {
            Log.e(TAG, "SvgDecoder decode", ex)
            null
        }
    }

    private fun loadSVGContent(isSelected: Boolean, svgPath: String): String {
        if (!File(svgPath).exists()) {
            Log.w(TAG, "loadSVGImage $svgPath is not exist,return")
            return ""
        }
        var svgContent = readTxtFile(svgPath)
        if (svgContent.isEmpty()) {
            Log.w(TAG, "loadSVGImage content is null,return")
            return ""
        }
        if (isSelected) {
            svgContent = svgContent.replace(THUMBNAIL_DEFAULT_COLOR, THUMBNAIL_SELECTED_COLOR)
        }
        return svgContent
    }

    private fun readTxtFile(strFilePath: String): String {
        if (strFilePath.isEmpty()) {
            return ""
        }
        val file = File(strFilePath)
        if (file.exists().not()) {
            return ""
        }
        // 文件内容字符串
        var content = ""
        var inStream: InputStream? = null
        try {
            inStream = FileInputStream(file)
            var line: String? = null
            val buffReader =
                BufferedReader(InputStreamReader(FileInputStream(strFilePath), "UTF-8"))
            // 分行读取
            while (buffReader.readLine().also { line = it } != null) {
                content += "$line"
            }
        } catch (e: FileNotFoundException) {
            Log.e(TAG, "readTxtFile", e)
        } catch (e: IOException) {
            Log.e(TAG, "readTxtFile", e)
        } finally {
            try {
                inStream?.close()
            } catch (e: IOException) {
                Log.e(TAG, "readTxtFile", e)
            }
        }
        return content
    }
}